package com.flydog.taskManager.security.config;

import com.flydog.taskManager.entity.user.AdminUser;
import com.flydog.taskManager.repository.AdminUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * spring security 工具方法
 *
 * @author caoweidong
 * @version 0.0.0
 * @create 2021/6/17 10:05
 */
@Component
public class SecurityUtil {
    @Autowired
    AdminUserRepository userRepository;

    public AdminUser getAuthedUser(){
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Optional<AdminUser> optionalAdminUser = userRepository.findByName(userDetails.getUsername());
        return optionalAdminUser.orElse(null);
    }

    public Long getAuthUserId() {
        return getAuthedUser().getId();
    }
}
